package org.example.innovate.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.example.innovate.service.OssService;
import org.example.innovate.util.OSSClientUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String publishImgToOSS(MultipartFile file,String dataPath) {
        // 工具类取值
        String endPoint = OSSClientUtil.getEndPoint();
        String accessKeyId = OSSClientUtil.getAccessKeyId();
        String accessKeySecret = OSSClientUtil.getAccessKeySecret();
        String bucketName = OSSClientUtil.getBucketName();
        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 3 拼接
            fileName = "food_moment_discover/train/data/" + dataPath + "/" + fileName;
            // 4 调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            // 5 关闭ossClient
            ossClient.shutdown();
            // 把上传之后的文件路径返回  需要符合阿里云oss的上传路径
            // https://nsx-fitness.oss-cn-guangzhou.aliyuncs.com/..
            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
